class ExtensionTask < Rake::TaskLib

  def initialize name, dir, *deps
    define name, dir, *deps
  end


  private

  def needs_regeneration? source, bundle
    return true unless File.exists? bundle
    return true unless File.mtime(bundle) > File.mtime(source)
  end

  def define name, dir, *deps
    namespace :compile do
      desc "Compile the #{name} C extension"
      task name do
        ext = "#{dir}/#{name}"
        if needs_regeneration? "#{ext}.c", "#{ext}.bundle"
          Rake::Task["clobber_#{name}_ext"].execute
          Dir.chdir(dir) do
            ruby 'extconf.rb'
            sh   'make'
          end
          cp "#{ext}.bundle", "lib/accessibility/#{name}/"
        end
      end
    end
    task :compile => "compile:#{name}"

    deps.each do |dep|
      task "compile:#{name}" => "compile:#{dep}"
    end

    clobber_task = "clobber_#{name}_ext"
    desc "Remove files generated by compiling #{name}"
    task clobber_task do
      Dir.glob("{lib,ext}/**/#{name}{.bundle,.o}").each do |file|
        $stdout.puts "rm #{file}"
        rm_f file
      end
      file = "#{dir}/Makefile"
      $stdout.puts "rm #{file}"
      rm_f file
    end
    task :clobber => clobber_task
  end

end


ExtensionTask.new 'bridge',         'ext/accessibility/bridge'
ExtensionTask.new 'extras',         'ext/accessibility/extras',         'bridge'
ExtensionTask.new 'core',           'ext/accessibility/core',           'bridge', 'extras'
ExtensionTask.new 'highlighter',    'ext/accessibility/highlighter',    'bridge', 'extras'
ExtensionTask.new 'screen_shooter', 'ext/accessibility/screen_shooter', 'bridge'
